<template>
	<div class="form_text">
		<span v-if="isPlaceholder" class="placeholder">{{placeholder}}</span>
		<p :contenteditable="!disabled" tabindex='true'  v-on:input="updateValue($event)" @click="get_focus($event)" v-text="value"></p>
		<input type="text" v-bind:disabled="!isEdit" v-bind:value="value" />
	</div>
</template>

<script>
	import $ from 'jquery';
	export default {
		props: {
			value: {
				default: ''
			},
			aligned: {
				type: String,
				default: 'left'
			},
			isEdit: {
				type: Boolean,
				default: true
			},
			placeholder: {
				type: String,
				default: ''
			},
			disabled: {
				type: Boolean,
				default: false
			}
		},
		computed: {
			_aligned() {
				return('text-' + this.aligned)
			}
		},
		data() {
			return {
				isPlaceholder: true
			}
		},
		watch: {
			value(val) {
				if(val) {
					this.isPlaceholder = false;
				}
			}
		},
		mounted() {
			console.log(this.value)
			if(this.value) {
				this.isPlaceholder = false;
			}
		},
		methods: {
			get_focus(event) {
				event.target.focus()
			},
			updateValue: function(event) {
				console.log('aa')
				this.isPlaceholder = false;
				var formattedValue = $(event.target).text()
				console.log(formattedValue.length)
				if(formattedValue.length>50){
					formattedValue = formattedValue.substring(0,50)
					event.target.blur()
					setTimeout(function(){
						event.target.innerHTML = formattedValue;
					},10)
					
//					event.target.focus()
//					this.setCursorPosition(event.target,formattedValue.length,formattedValue)
				}
				if(!$(event.target).text()) {
					this.isPlaceholder = true;
				}
				this.$emit('input', formattedValue)
			},
			setCursorPosition(elem, index,txt) {
			    var val = txt
			    var len = val.length			 
			    // 超过文本长度直接返回
			    if (len < index) return
			    setTimeout(function() {
			        elem.focus()
			        if (elem.setSelectionRange) { // 标准浏览器
			            elem.setSelectionRange(index, index)   
			        } else { // IE9-
			            var range = elem.createTextRange()
			            range.moveStart("character", -len)
			            range.moveEnd("character", -len)
			            range.moveStart("character", index)
			            range.moveEnd("character", 0)
			            range.select()
			        }
			    }, 10)
			}
		}
	}
</script>

<style lang="less" scoped="scoped">
	@import 'index.less';
	@import '../variables.less';
	@import '../../common/less/base.less';
	.form_text {
		display: inline-block;
		width: 100%;
		position: relative;
		input {
			height: 0;
			width: 0;
			opacity: 0.1;
			z-index: -1;
			position: absolute;
		}
		.placeholder {
			position: absolute;
			top: 15*@base_size_t;
			left: 15*@base_size_t;
			color: lightgray;
		}
		p {
			width: 100%;
			display: inline-block;
			min-height: 50px;
			border: 1px solid lighten(@color-border, 10%);
			padding-top: 15*@base_size_t;
			padding-left: 15*@base_size_t;
			padding-bottom: 15*@base_size_t;
		}
	}
</style>